using System.Security.Claims;
using Identity.Application.Contracts.Common;
using Identity.Application.Contracts.Services;
using Identity.Application.UserAggregates.Commands;
using MediatR;
using Microsoft.IdentityModel.JsonWebTokens;

namespace Identity.Application.UserAggregates.CommandHandler;

public class LoginUserCommandHandler : IRequestHandler<LoginUserCommand, Result>
{
    private readonly IUserService _userService;
    private readonly ITokenService _tokenService;
    private readonly IRedisService _redisService;
    public LoginUserCommandHandler(IUserService userService, ITokenService tokenService, IRedisService redisService)
    {
        _userService = userService;
        _tokenService = tokenService;
        _redisService = redisService;
    }
    public async Task<Result> Handle(LoginUserCommand dto, CancellationToken cancellationToken)
    {
        var user = await _userService.GetUserByNameAsync(dto.userName);
        if (user == null) return Result.Failure("用户不存在");

        var passwordValid = await _userService.CheckPasswordAsync(user.Id, dto.password);
        if (!passwordValid.Succeeded) return Result.Failure("密码错误");

        var isconfirmed =await _userService.IsEmailConfirmedAsync(user.Id);
        if (!isconfirmed) return Result.Failure("邮箱未认证，请先认证邮箱！");
           
        var nonce = Guid.NewGuid().ToString();
        var claims = new List<Claim>
        {
           new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
           new Claim(JwtRegisteredClaimNames.Name, user.UserName.ToString()),
           new Claim("nonce", nonce)
        };
        var tempToken = _tokenService.GenerateTemporaryToken(claims);

        // Redis 保存 nonce，过期时间和 token 一样
        await _redisService.SetStringAsync($"login_nonce:{nonce}", "1", TimeSpan.FromMinutes(5));

        return Result.Success(new { temp_token =  tempToken});

    }
}